package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 20:04
 * @since JDK 1.6
 */
public class DoubleConverter implements Converter<Double> {
    @Override
    public Double convert(Object value) {
        if (value == null) {
            return null;
        }

        if (value.getClass() == Double.class) {
            return (Double) value;
        }
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        if (value instanceof Boolean) {
            return (Boolean) value ? Double.valueOf(1) : Double.valueOf(0);
        }

        try {
            String stringValue = value.toString().trim();
            return Double.valueOf(stringValue);
        } catch (NumberFormatException e) {
            throw new TypeConversionException(value, e);
        }
    }
}
